<?php

namespace app\api\model;

use think\Model;

class SystemOrganization extends Model
{
    // 表名
    protected $name = 'system_organization';

    // 自动时间戳
    protected $autoWriteTimestamp = true;
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';

    // 类型转换
    protected $type = [
        'sort'   => 'integer',
        'status' => 'integer',
        'pid'    => 'integer'
    ];

    /**
     * 获取菜单树
     */
    public function getMenuTree($where = [])
    {
        $menus = $this->where($where)
            ->order('sort asc, id asc')
            ->select();

        return $this->buildTree($menus->toArray(), 0);
    }

    /**
     * 构建树形结构
     */
    private function buildTree($menus, $pid)
    {
        $tree = [];
        foreach ($menus as $menu) {
            if ($menu['pid'] == $pid) {
                $children = $this->buildTree($menus, $menu['id']);
                if ($children) {
                    $menu['children'] = $children;
                }
                $tree[] = $menu;
            }
        }
        return $tree;
    }
}